import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk


def center_window(root, width, height):
    """使窗口居中显示"""
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x_coordinate = (screen_width / 2) - (width / 2)
    y_coordinate = (screen_height / 2) - (height / 2)
    root.geometry(f"{width}x{height}+{int(x_coordinate)}+{int(y_coordinate)}")


def get_screen_dimensions():
    """
    获取屏幕尺寸。
    """
    root = tk.Tk()
    root.withdraw()  # 隐藏Tkinter的根窗口
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    root.destroy()  # 销毁临时创建的窗口
    return screen_width, screen_height


def load_image(file_path):
    """加载图片并转换为Tkinter支持的格式"""
    image = Image.open(file_path)
    photo = ImageTk.PhotoImage(image)
    return photo


def adjust_image_size(
    event, background_label, window, screen_dimensions, preprocessed_max_img
):
    """根据窗口大小调整图片大小，并计划更新背景图片，增加尺寸变化阈值判断"""
    global img_original, last_size
    new_width, new_height = event.width, event.height
    screen_width, screen_height = screen_dimensions

    # 判断窗口尺寸是否接近屏幕尺寸，这里使用一个容差值来近似判断最大化
    tolerance_percentage = 5  # 容差，根据需要调整
    is_nearly_maximized = (
        abs((screen_width - new_width) / screen_width * 100) <= tolerance_percentage
        and abs((screen_height - new_height) / screen_height * 100)
        <= tolerance_percentage
    )
    # print("窗口尺寸：", new_width, new_height, "屏幕尺寸：", screen_width, screen_height, "是否接近屏幕尺寸：", is_nearly_maximized, "窗口尺寸是否真正发生变化：", new_width != last_size[0] or new_height != last_size[1])
    # 检查窗口尺寸是否真正发生变化
    if new_width != last_size[0] or new_height != last_size[1]:
        last_size = (new_width, new_height)

        def resize_and_update():
            if is_nearly_maximized:  # 检查窗口是否最大化
                print("窗口最大化")
                update_background_image(preprocessed_max_img, background_label)
            else:
                img_resized = img_original.resize(
                    (new_width, new_height), Image.Resampling.BILINEAR
                )
                new_bg_image = ImageTk.PhotoImage(img_resized)
                update_background_image(new_bg_image, background_label)

        # 使用after方法延迟执行图像缩放和更新，减少即时响应带来的卡顿感
        window.after(0, resize_and_update)  # 参数0表示尽可能快地执行，但仍在事件队列中


def load_and_preprocess_image(image_path, screen_dimensions):
    """
    加载图像并根据屏幕尺寸预处理至接近但不超过屏幕大小。
    """
    original_image = Image.open(image_path)
    img_width, img_height = original_image.size
    screen_width, screen_height = screen_dimensions

    # 计算保持原图比例下，不超过屏幕尺寸的最大尺寸
    if img_width > img_height:  # 图片宽大于高
        new_width = max(img_width, screen_width)
        new_height = int(new_width * img_height / img_width)
    else:  # 图片高大于宽或两者相等
        new_height = max(img_height, screen_height)
        new_width = int(new_height * img_width / img_height)

    print(f"原始尺寸: {img_width}x{img_height} 新尺寸: {new_width}x{new_height}")
    img_resized = original_image.resize(
        (new_width, new_height), Image.Resampling.BILINEAR
    )
    return img_resized


def set_background_image(window, image_path):
    """设置窗口背景图片，并在窗口大小变化时调整图片大小"""
    screen_dimensions = get_screen_dimensions()
    global img_original, background_label, last_size
    img_original = Image.open(image_path)
    bg_image = load_image(image_path)
    preprocessed_img_resized = load_and_preprocess_image(image_path, screen_dimensions)
    preprocessed_max_img = ImageTk.PhotoImage(preprocessed_img_resized)
    last_size = (0, 0)  # 初始化上次窗口大小为(0, 0)，确保首次加载图片
    background_label = tk.Label(window, image=bg_image)
    background_label.place(relwidth=1, relheight=1)
    window.bind(
        "<Configure>",
        lambda event: adjust_image_size(
            event, background_label, window, screen_dimensions, preprocessed_max_img
        ),
    )


def update_background_image(new_bg_image, label):
    """安全地更新背景图片"""
    label.configure(image=new_bg_image)
    label.image = new_bg_image


def set_tree_row_color(tree, item_id, background_color, foreground_color):
    # 为指定行分配一个唯一的标签，如果还没有标签的话
    if not tree.item(item_id, "tags"):
        tree.item(item_id, tags=("custom_tag"))
    else:
        # 如果已经有了标签，就使用已有的标签
        tree.item(item_id, tags=("custom_tag"))

    # 配置标签的样式
    tree.tag_configure(
        "custom_tag", background=background_color, foreground=foreground_color
    )


def insert_colored_line(text_widget, text, color="blue"):
    """在Text小部件中插入带有指定颜色的文本行"""
    # 定义文本颜色标签
    text_widget.tag_configure(color, foreground=color)

    # 插入文本并应用颜色标签
    end_index = text_widget.index(tk.END)
    # 确保插入点在末尾，如果有换行符则跳过它
    if text_widget.get(end_index, tk.END).strip() == "":
        text_widget.insert(tk.END, text + "\n", color)
    else:
        text_widget.insert(tk.END, "\n" + text + "\n", color)
    text_widget.see(tk.END)


class TreeToolTip:
    def __init__(self, treeview):
        self.treeview = treeview
        self.tipwindow = None
        self.id = None
        self.x = self.y = 0

    def showtip(self, event, text):
        self.hidetip()
        """Display text in tooltip window based on mouse event in Treeview."""
        if self.tipwindow or not text:
            return
        item_id = self.treeview.identify_row(event.y)
        if item_id:
            bbox = self.treeview.bbox(item_id)
            if bbox:  # Ensure the item is visible and has a bounding box.
                x = bbox[0] + self.treeview.winfo_rootx() + 27
                y = bbox[1] + self.treeview.winfo_rooty() + 22
                self.tipwindow = tw = tk.Toplevel(self.treeview)
                tw.wm_overrideredirect(1)
                tw.wm_geometry("+%d+%d" % (x, y))
                label = tk.Label(
                    tw,
                    text=text,
                    background="#ffffe0",
                    relief="solid",
                    borderwidth=1,
                    font=("tahoma", "8", "normal"),
                )
                label.pack(ipadx=1)
        else:
            pass

    def hidetip(self):
        tw = self.tipwindow
        self.tipwindow = None
        if tw:
            tw.destroy()


def show_edit_window(app, id_value, name_value, password_value):
    edit_window = tk.Toplevel(app)
    edit_window.title("编辑个人信息")
    center_window(edit_window, 300, 200)
    # 设置网格列权重，使得第二列可以扩展
    edit_window.grid_columnconfigure(1, weight=1)
    for i in range(4):  # 设置四行可扩展
        edit_window.grid_rowconfigure(i, weight=1)
    # 创建标签和输入框
    tk.Label(edit_window, text="ID:").grid(row=0, column=0)
    id_entry = tk.Entry(edit_window)
    id_entry.insert(0, id_value)  # 预填充ID值
    id_entry.config(state="readonly")  # 设置ID输入框为只读
    id_entry.grid(row=0, column=1, sticky="nsew")

    tk.Label(edit_window, text="姓名:").grid(row=1, column=0)
    name_entry = tk.Entry(edit_window)
    name_entry.insert(0, name_value)  # 预填充姓名值
    name_entry.grid(row=1, column=1, sticky="nsew")

    tk.Label(edit_window, text="密码:").grid(row=2, column=0)
    password_entry = tk.Entry(edit_window, show="*")  # 密码输入框显示为星号
    password_entry.insert(0, password_value)  # 预填充密码值
    password_entry.grid(row=2, column=1, sticky="nsew")

    # 提交按钮
    def submit_changes():
        new_name = name_entry.get()
        new_password = password_entry.get()
        print(f"修改后的姓名: {new_name}, 修改后的密码: {new_password}")
        edit_window.destroy()  # 关闭编辑窗口

    submit_button = tk.Button(edit_window, text="提交", command=submit_changes)
    submit_button.grid(row=3, columnspan=2, sticky="nsew")
